package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.file.service.FileStorageService;
import com.heima.model.wemedia.pojos.WmBaiduToken;
import com.heima.utils.baidu.Base64Util;
import com.heima.utils.baidu.HttpUtil;
import com.heima.wemedia.mapper.WmBaiduTokenMapper;
import com.heima.wemedia.service.GreenScanService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * @author 陈辉
 * @data 2023 19:39
 */
@Service
@Slf4j
public class GreenScanServiceImpl implements GreenScanService {
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmBaiduTokenMapper wmBaiduTokenMapper;
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    @Value("${baidu.apiKey}")
    private String apiKey;
    @Value("${baidu.apiSecret}")
    private String apiSecret;

    /**
     * 审核文本
     *
     * @param text
     * @return
     */
    @Override
    public Map scanText(String text) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            String param = "text=" + URLEncoder.encode(text, "utf-8");

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            WmBaiduToken wmBaiduToken = wmBaiduTokenMapper.selectList(null).get(0);
            String accessToken = wmBaiduToken.getToken();

            String result = HttpUtil.post(url, accessToken, param);
            Map map = JSON.parseObject(result, Map.class);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 审核图片
     *
     * @param imageUrl
     * @return
     */
    @Override
    public Map scanImage(String imageUrl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
        try {
            // 本地文件路径
            byte[] imgData = fileStorageService.downLoadFile(imageUrl);

            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            WmBaiduToken wmBaiduToken = wmBaiduTokenMapper.selectList(null).get(0);
            String accessToken = wmBaiduToken.getToken();
            //String accessToken = "24.19aeb6a4a8031793153eb2cbdfc4aa0e.2592000.1688981228.282335-34639831";

            String result = HttpUtil.post(url, accessToken, param);
            return JSON.parseObject(result, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 刷新token
     */
    @Override
//    @Scheduled(cron = "0/5 * * * * ?")
    public void refreshToken() {
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?client_id=" + apiKey +
                            "&client_secret=" + apiSecret + "&grant_type=client_credentials")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String access_token = JSON.parseObject(response.body().string()).get("access_token").toString();
            log.info("生成百度API-token成功：{}", access_token);
            WmBaiduToken wmBaiduToken = WmBaiduToken.builder().token(access_token).createdTime(new Date()).build();
            wmBaiduTokenMapper.insert(wmBaiduToken);

            //删除上一个token
            wmBaiduTokenMapper.delete(Wrappers.<WmBaiduToken>lambdaQuery().lt(WmBaiduToken::getId, wmBaiduToken.getId()));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成百度API-token失败：{}", e.getMessage());
        }
    }
}